package com.example.flowermall.controller;

import com.example.flowermall.config.VerifyCode;
import com.example.flowermall.entity.Result;
import com.example.flowermall.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
public class VerifyCodeController {
    @Autowired
    private RedisUtil redisUtil;
    @GetMapping("/vscode")
    public Result code(HttpServletRequest httpServletRequest) throws IOException {
        VerifyCode verifyCode=new VerifyCode();
        BufferedImage image = verifyCode.getImage();
        String text = verifyCode.getText();
        UUID uuid = UUID.randomUUID();
        redisUtil.setCacheObject("captcha_code"+ uuid,text,2, TimeUnit.MINUTES);
        HttpSession session=httpServletRequest.getSession();
        session.setAttribute("index_code",text);
        //VerifyCode.output(image, httpServletResponse.getOutputStream())
        String base64 = VerifyCode.output(image, new FastByteArrayOutputStream());
        Result result = Result.success();
        result.put("captcha",uuid);
        result.put("img",base64);
        return result;
    }
}
